package thread.queue.waitNotify;

import thread.queue.Consumer;
import thread.queue.Producer;
import thread.queue.Store;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by xu on 2021/12/5.
 */
public class StoreWhileWait implements Store{
    //最大保存限制
    private final  int MAX_LIMIT = 10;
    private List<String> list = new ArrayList();

    public void  produce(String t) throws InterruptedException {
        synchronized (list){
            while (list.size()>MAX_LIMIT){
                System.out.println("生产过量等待消费者消费----"+list.size());
                list.wait();
            }
            Thread.sleep(new Random().nextInt(500)+200);
            System.out.println("生产资源:"+Thread.currentThread().getId()+",param:"+t.toString() +",size:"+list.size());
            list.add(t);
            list.notifyAll();

        }

    }

    public void consume() throws InterruptedException {
        synchronized (list){
            while (list.size()==0){
                System.out.println("暂无资源可以消费----"+list.size());
                list.wait();
            }
            //消费
            String t = list.get(0);
            System.out.println("消费资源："+t.toString()+",size:"+list.size());
            Thread.sleep(1000);
            list.remove(0);
            list.notifyAll();
        }

    }

    public static void main(String[] args) {
        Store store = new StoreWhileWait();

        Producer p1 =  new Producer(store);
        Producer p2 =  new Producer(store);
        Producer p3 =  new Producer(store);
        new  Thread(p1).start();
        new  Thread(p2).start();
        new  Thread(p3).start();
        Consumer c1 =  new Consumer(store);
        new  Thread(c1).start();

    }


}
